/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CaixaFrame.java
 *
 * Created on Aug 10, 2011, 10:39:37 AM
 */
package br.com.tbp.gui.financeiro;

import br.com.tbp.controle.ControleLancamento;
import br.com.tbp.exception.PersistenciaException;
import br.com.tbp.model.domain.financeiro.Lancamento;
import br.com.tbp.model.domain.financeiro.TipoConta;
import br.com.tbp.utils.DateUtils;
import com.towel.swing.table.TableFilter;
import java.util.Calendar;
import java.util.List;

/**
 *
 * @author Diego
 */
public class CaixaFrame extends javax.swing.JFrame {

    private LancamentosTableModel model;
    private TableFilter filter;
    private int mes;
    private int ano;
    private java.text.DecimalFormat df = new java.text.DecimalFormat("###,###,##0.00");

    public CaixaFrame(int mes, int ano) {
        initComponents();
        this.mes = mes;
        this.ano = ano;
        setLocationRelativeTo(null);
        this.carregaLancamentos(mes, ano);
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        popup = new javax.swing.JPopupMenu();
        option1 = new javax.swing.JMenuItem();
        option2 = new javax.swing.JMenuItem();
        option3 = new javax.swing.JMenuItem();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        entradasLabel = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        saidasLabel = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        totalLabel = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        tituloLabel = new javax.swing.JLabel();
        jPanel4 = new javax.swing.JPanel();
        jPanel5 = new javax.swing.JPanel();
        novoLink = new org.jdesktop.swingx.JXHyperlink();
        estornarLink = new org.jdesktop.swingx.JXHyperlink();
        imprimirLink = new org.jdesktop.swingx.JXHyperlink();
        listarLink = new org.jdesktop.swingx.JXHyperlink();
        jPanel6 = new javax.swing.JPanel();
        scrollpane = new javax.swing.JScrollPane();
        tabela = new javax.swing.JTable();
        jPanel7 = new javax.swing.JPanel();
        msgLabel = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        inputTextField = new javax.swing.JFormattedTextField();
        okButton = new javax.swing.JButton();

        option1.setText("Option 1");
        popup.add(option1);

        option2.setText("Option 2");
        popup.add(option2);

        option3.setText("Option 3");
        popup.add(option3);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("TBP - Caixa");

        jPanel1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(153, 153, 153), 1, true));

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 20));
        jLabel1.setText("(+) Entradas (R$):");

        entradasLabel.setFont(new java.awt.Font("Tahoma", 1, 24));
        entradasLabel.setForeground(new java.awt.Color(0, 153, 51));
        entradasLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        entradasLabel.setText("19.000,00");

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 20));
        jLabel3.setText("(-) Saídas (R$):");

        saidasLabel.setFont(new java.awt.Font("Tahoma", 1, 24));
        saidasLabel.setForeground(new java.awt.Color(255, 51, 0));
        saidasLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        saidasLabel.setText("4.000,00");

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 20));
        jLabel5.setText("Total (R$):");

        totalLabel.setFont(new java.awt.Font("Tahoma", 1, 24));
        totalLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        totalLabel.setText("15.000,00");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel1)
                    .addComponent(jLabel5))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(totalLabel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE)
                    .addComponent(saidasLabel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(entradasLabel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(20, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(entradasLabel)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saidasLabel)
                    .addComponent(jLabel3))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(totalLabel)
                    .addComponent(jLabel5))
                .addContainerGap())
        );

        jPanel2.setLayout(new java.awt.BorderLayout());

        jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        tituloLabel.setText("LANÇAMENTOS DO MES/ANO");
        jPanel3.add(tituloLabel);

        jPanel2.add(jPanel3, java.awt.BorderLayout.PAGE_START);

        jPanel4.setLayout(new java.awt.BorderLayout());

        jPanel5.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        novoLink.setForeground(new java.awt.Color(0, 153, 51));
        novoLink.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/plus_16.png"))); // NOI18N
        novoLink.setText("novo");
        novoLink.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                novoLinkActionPerformed(evt);
            }
        });
        jPanel5.add(novoLink);

        estornarLink.setForeground(new java.awt.Color(255, 51, 0));
        estornarLink.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/delete.png"))); // NOI18N
        estornarLink.setText("estornar");
        estornarLink.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                estornarLinkActionPerformed(evt);
            }
        });
        jPanel5.add(estornarLink);

        imprimirLink.setForeground(new java.awt.Color(102, 102, 102));
        imprimirLink.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/print_16.png"))); // NOI18N
        imprimirLink.setText("imprimir");
        imprimirLink.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                imprimirLinkMousePressed(evt);
            }
        });
        jPanel5.add(imprimirLink);

        listarLink.setForeground(new java.awt.Color(51, 51, 0));
        listarLink.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/abrir.png"))); // NOI18N
        listarLink.setText("listar todas");
        listarLink.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                listarLinkActionPerformed(evt);
            }
        });
        jPanel5.add(listarLink);

        jPanel4.add(jPanel5, java.awt.BorderLayout.PAGE_START);

        jPanel6.setLayout(new java.awt.BorderLayout());

        tabela.setFont(new java.awt.Font("Dialog", 0, 13));
        tabela.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        tabela.setRowHeight(22);
        tabela.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        scrollpane.setViewportView(tabela);

        jPanel6.add(scrollpane, java.awt.BorderLayout.CENTER);

        jPanel7.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        msgLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/anexo.png"))); // NOI18N
        msgLabel.setText("mensagem");
        jPanel7.add(msgLabel);

        jPanel6.add(jPanel7, java.awt.BorderLayout.PAGE_END);

        jPanel4.add(jPanel6, java.awt.BorderLayout.CENTER);

        jPanel2.add(jPanel4, java.awt.BorderLayout.CENTER);

        jLabel8.setText("Busca rápida");

        inputTextField.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 5, 1, 1));
        inputTextField.setToolTipText("Selecione o filtro abaixo e digite para buscar");
        inputTextField.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);
        inputTextField.setFont(new java.awt.Font("Dialog", 0, 15));
        inputTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                inputTextFieldActionPerformed(evt);
            }
        });

        okButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/search_16.png"))); // NOI18N
        okButton.setToolTipText("Informe o nome da conta e clique para buscar");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 799, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel8)
                            .addComponent(inputTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 338, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(okButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel8)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(inputTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 478, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void novoLinkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_novoLinkActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_novoLinkActionPerformed

    private void estornarLinkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_estornarLinkActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_estornarLinkActionPerformed

    private void inputTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_inputTextFieldActionPerformed
        buscaLancamento(inputTextField.getText());
}//GEN-LAST:event_inputTextFieldActionPerformed

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        buscaLancamento(inputTextField.getText());
}//GEN-LAST:event_okButtonActionPerformed

    private void listarLinkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_listarLinkActionPerformed
        inputTextField.setText(null);
        inputTextField.requestFocus();
        this.carregaLancamentos(this.mes, this.ano);
    }//GEN-LAST:event_listarLinkActionPerformed

    private void imprimirLinkMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_imprimirLinkMousePressed
        popup.show(evt.getComponent(), evt.getX(), evt.getY());
    }//GEN-LAST:event_imprimirLinkMousePressed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                int mes = DateUtils.getMesAtual();
                int ano = DateUtils.getAnoAtual();
                new CaixaFrame(mes + 1, ano).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel entradasLabel;
    private org.jdesktop.swingx.JXHyperlink estornarLink;
    private org.jdesktop.swingx.JXHyperlink imprimirLink;
    private javax.swing.JFormattedTextField inputTextField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private org.jdesktop.swingx.JXHyperlink listarLink;
    private javax.swing.JLabel msgLabel;
    private org.jdesktop.swingx.JXHyperlink novoLink;
    private javax.swing.JButton okButton;
    private javax.swing.JMenuItem option1;
    private javax.swing.JMenuItem option2;
    private javax.swing.JMenuItem option3;
    private javax.swing.JPopupMenu popup;
    private javax.swing.JLabel saidasLabel;
    private javax.swing.JScrollPane scrollpane;
    private javax.swing.JTable tabela;
    private javax.swing.JLabel tituloLabel;
    private javax.swing.JLabel totalLabel;
    // End of variables declaration//GEN-END:variables

    private void carregaLancamentos(int mes, int ano) {
        this.carregaTitulo(mes, ano);
        this.pesquisarLancamentos(mes, ano);
    }

    private void carregaTitulo(int mes, int ano) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.MONTH, mes);
        StringBuilder sb = new StringBuilder("LANÇAMENTOS DE ").append(DateUtils.getMesComoString(c.getTime()).toUpperCase()).append(" ").append(ano);
        tituloLabel.setText(sb.toString());
    }

    private void pesquisarLancamentos(int mes, int ano) {
        try {
            ControleLancamento controle = new ControleLancamento();
            List<Lancamento> lista = controle.pesquisar(mes, ano);
            this.updateTable(lista);
            this.updateValores(lista);
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        }
    }

    private void updateTable(List<Lancamento> lista) {
        model = new LancamentosTableModel(lista);

        tabela.setModel(model);
        /* Comportamentos adicionais: filtrar e ajustar o o tamanho das colunas */
        filter = new TableFilter(tabela);
        //JTableUtils.fitAllColumns(tabela);

        if (model.getRowCount() > 0) {
            tabela.getColumnModel().getColumn(0).setPreferredWidth(30);
            tabela.getColumnModel().getColumn(1).setPreferredWidth(30);
            tabela.getColumnModel().getColumn(2).setPreferredWidth(350);
            tabela.getColumnModel().getColumn(3).setPreferredWidth(50);
        }
        int linhas = model.getRowCount();
        String contas = linhas != 1 ? linhas + " lançamentos registrados" : linhas + " lançamento registrado";
        msgLabel.setText("Exibindo " + contas);
    }

    private void buscaLancamento(String texto) {
        if ((texto == null) || (texto.isEmpty())) {
            this.pesquisarLancamentos(this.mes, this.ano);
        } else {
            try {
                ControleLancamento controle = new ControleLancamento();
                List<Lancamento> lista = controle.pesquisarPor(texto);
                
                this.updateTable(lista);

                inputTextField.selectAll();
            } catch (PersistenciaException pex) {
                System.out.println(pex.getMessage());
            }
        }
    }

    private void updateValores(List<Lancamento> lista) {
        Double entradas = 0d;
        Double saidas = 0d;
        for(Lancamento lc : lista) {
            if(lc.getTipo().equals(TipoConta.ENTRADA)) {
                entradas += lc.getTotal();
            } else if(lc.getTipo().equals(TipoConta.SAIDA)) {
                saidas += lc.getTotal();
            }
        }
        Double total = entradas - saidas;
        entradasLabel.setText(df.format(entradas));
        saidasLabel.setText(df.format(saidas));
        totalLabel.setText(df.format(total));
    }
}
